package query;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.jdom.JDOMException;
import storage.IDataStorage;
import storage.XmlDataStorage;
import storage.beans.SimulationBean;

public class Query {
  private IDataStorage storage = new XmlDataStorage();
  private int tilt;
  private float eccentricity;
  private long startDateTime;
  private long endDateTime;
  
  public Query(int tilt, float eccentricity, long startDateTime, long endDateTime) {
    this.tilt = tilt;
    this.eccentricity = eccentricity;
    this.startDateTime = startDateTime;
    this.endDateTime = endDateTime;
  }
  
  /**
   * 1. search saved simulations
   * 2. if the simulation exists get the bean
   *    a. if more than one simulation exists, rate the simulations based on the following scales
   *      -regions are more important than time ranges because we don't have to run simulations 
   *       for mismatched regions; the bigger the region the better (less interpolation needed)
   *      -the bigger the time range the better (greater chance of matching the query's request)
   *      -if there are still matching simulations, pick the one that was run last
   *      
   *    b. check start date/time; if it is outside the range of the query date/time return null
   *    c. if (a) passes, check the latitude/longitude settings; perform interpolation calculations to get the missing regions
   * 3. if a simulation does not exist return null
   * 
   * @author andrew
   *
   */
  public SimulationBean run() throws JDOMException, IOException {
    SimulationBean bean = null;
    List simulations = storage.getSimulations(tilt, eccentricity);
    if(simulations.size() == 0) {
      //do nothing
    }
    else if(simulations.size() == 1) {
      SimulationBean storedBean = (SimulationBean)simulations.get(0);
      if(storedBean.getStartDateTime() >= startDateTime &&
         storedBean.getEndDateTime() <= endDateTime)
        bean = storedBean;
    }
    else {      
      Collections.sort(simulations);
      
      //the preceding call sorts in ascending order so start from the bottom (the highest ranked Simulation) 
      //and take the first bean that doesn't violate the date range
      for(int i = simulations.size()-1; i >= 0; i--) {
        SimulationBean storedBean = (SimulationBean)simulations.get(i);
        if(storedBean.getStartDateTime() >= startDateTime &&
           storedBean.getEndDateTime() <= endDateTime) {
          bean = storedBean;
          break;
        }
      }
    }
    return bean;
  }
}
